package com.ccc3gc.dao.impl;

import com.ccc3gc.dao.UserDao;
import com.ccc3gc.entity.User;
import com.ccc3gc.util.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    JdbcTemplate jdbcTemplate = JdbcUtils.getJdbcTemplate();

    @Override
    public User selectUserByUserName(String userName) {
        String sql = "select * from t_user where user_name = ?";
        List user = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), userName);
        return user.isEmpty() ? null : (User) user.get(0);
    }

    @Override
    public User selectUserById(int id) {
        String sql = "select * from t_user where user_id = ?";
        List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), id);
        return query.isEmpty() ? null : query.get(0);
    }

    @Override
    public List<User> selectUserByPage(int startRow, int pageSize, String keyWord) {
        String sql = "select * from t_user where user_name like concat('%',?,'%') order by user_id desc limit ?,?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), keyWord, pageSize * (startRow - 1), pageSize);
    }

    @Override
    public int selectUserCount(String keyWord) {
        String sql = "select count(1) from t_user where user_name like concat('%',?,'%')";
        List<Integer> query = jdbcTemplate.query(sql, new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt(1);
            }
        }, keyWord);
        return query.get(0);
    }

    @Override
    public int insertUser(User user) {
        String sql = "insert into t_user(user_name,password,user_pic) values(?,?,?)";
        return jdbcTemplate.update(sql, user.getUserName(), user.getPassword(), user.getUserPic());
    }

    @Override
    public int updateUser(User user) {
        String sql = "update t_user set user_name = ?,user_pic = ? where user_id = ?";
        return jdbcTemplate.update(sql, user.getUserName(), user.getUserPic(), user.getUserId());
    }

    @Override
    public int deleteUser(int id) {
        String sql = "delete from t_user where user_id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<User> selectUserByKeyWord(String keyWord) {
        String sql = "select * from t_user where user_name like ?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), keyWord + "%");
    }
}
